<template>
  <el-card class="mt-20" shadow="hover">
    <div slot="header" class="clearfix">
      <el-button
        type="primary"
        size="small"
        :disabled="!category3Id"
        @click="goAddOrUpdateAttr"
        ><i class="el-icon-plus"></i> 添加属性</el-button
      >
    </div>
    <el-table :data="spuAttrList" border class="table-margin">
      <el-table-column type="index" label="序号" align="center" width="60px" />
      <el-table-column
        prop="attrName"
        label="属性名"
        align="center"
        width="100px"
      />
      <el-table-column label="属性值名称列表">
        <template v-slot="{ row }">
          <el-tag
            class="tag-margin"
            type="success"
            v-for="attrValue in row.attrValueList"
            :key="attrValue.id"
          >
            {{ attrValue.valueName }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120px" align="center">
        <template v-slot="{ row }">
          <el-button
            class="el-icon-edit"
            type="primary"
            size="small"
            @click="goUpdateAttr(row)"
          />
          <el-button class="el-icon-delete" type="danger" size="small" @click="deleteAttr(row)"/>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script>
import { mapState, mapMutations } from "vuex";
export default {
  name: "AttrList",
  data() {
    return {
      spuAttrList: [],
    };
  },
  methods: {
    ...mapMutations("attr", ["UPDATE_ATTRITEM"]),
    // 删除属性
    async deleteAttr(row){
      await this.$api.deleteAttr(row.id)
      this.$message.success("删除属性成功")
      this.getSpuAttrList()
    },
    // 修改属性
    goUpdateAttr(row) {
      this.UPDATE_ATTRITEM(row);
      this.goAddOrUpdateAttr()
    },
    // 获取SPU属性列表数据
    async getSpuAttrList() {
      if (!this.category3Id) return;
      const params = {
        category1Id: this.category1Id,
        category2Id: this.category2Id,
        category3Id: this.category3Id,
      };
      const res = await this.$api.getAttrList(params);
      this.spuAttrList = res.data;
    },
    // 清除SPU属性列表
    clearSpuAttrList() {
      this.spuAttrList = [];
    },
    // 跳转到添加/修改属性页面
    goAddOrUpdateAttr() {
      this.$emit("updateIsShow", "AddOrUpdateAttr");
    },
  },
  computed: {
    ...mapState("category", ["category1Id", "category2Id", "category3Id"]),
  },
  watch: {
    category3Id: {
      handler(newCategory3Id) {
        if (!newCategory3Id) {
          this.clearSpuAttrList();
          return;
        }
        this.getSpuAttrList();
      },
      immediate: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.mt-20 {
  margin-top: 20px;
}
.tag-margin {
  margin-right: 10px;
}
</style>
